﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageResize
{
    public class ImageResizer
    {
        public static Image ResizeImage(Image image, int width, int height)
        {
            // 创建一个Bitmap对象，它将包含调整大小后的图片
            Bitmap b = new Bitmap(width, height);

            // 设置高质量插值法
            b.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            // 使用Graphics对象绘制调整大小后的图片
            using (Graphics g = Graphics.FromImage(b))
            {
                // 设置高质量，低速度呈现平滑程度
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                // 清除画布
                g.Clear(Color.WhiteSmoke);

                // 在指定位置绘制源图片
                g.DrawImage(image, 0, 0, width, height);
            }

            // 将调整大小后的图片保存到文件
            return b;
        }

        public static void SaveImage(Image image, string path, ImageFormat format)
        {
            // 确保路径不为空
            if (string.IsNullOrEmpty(path))
                throw new ArgumentException("Path cannot be empty.");

            // 确保图片不为空
            if (image == null)
                throw new ArgumentNullException("Image cannot be null.");

            // 保存图片到指定路径
            image.Save(path, format);
        }
    }
}
